<template>
  <div>
  <div class="chatHome" v-if="isLogin">
    <div class="chatLeft">
      <div class="title">
        <h1>MiniChat</h1>
        <el-tag type="success">欢迎使用</el-tag>
        <br/>
      </div>
      <div class="online-person">
        <span class="onlin-text">聊天列表</span>
        
        <el-button class="add_btn" type="info" icon="el-icon-plus" size="small" circle @click="add">  </el-button>
        <div class="person-cards-wrapper">
          <!--会话对象-->
          <div
            class="personList"
            v-for="personInfo in personList"
            :key="personInfo.id"
            @click="clickPerson(personInfo)"
          >
            <PersonCard
            v-bind:personInfo="personInfo"
            v-bind:pcCurrent="pcCurrent"
            v-bind:user_id="user_id"
            @call-parent-method="del"
            ></PersonCard>
          </div>
        </div>
      </div>
    </div>
    <div class="chatRight">
      <!-- <router-view></router-view> -->
      <div v-if="showChatWindow">
        <ChatWindow
          :frinedInfo="chatWindowInfo"
          :nowFunc="nowFunc"
          @personCardSort="personCardSort"
        ></ChatWindow>
      </div>
      <div class="showIcon" v-else>
        <span class="iconfont icon-snapchat"></span>
        <!-- <img src="@/assets/img/snapchat.png" alt="" /> -->
      </div>
    </div>
    <!-- <el-col :span="4"><div class="grid-content bg-purple"></div></el-col> -->
  </div>

   <!--登录注册弹窗-->
   <div>
      <el-dialog
      title="用户登录"
      :visible.sync="showLogin"
      width="40%"
      center>
      <span>
        <el-form :label-position="labelPosition" :rules="rules" label-width="80px" :model="userModel">
         <el-form-item label="用户名">
         <el-input v-model="userModel.username"></el-input>
         </el-form-item>
         <el-form-item label="密码">
          <el-input v-model="userModel.password"></el-input>
         </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="login">登录</el-button>
      <el-button @click="showLogin = false;showRegister = true">前往注册</el-button>
      </span>
      </el-dialog>
    </div>
    <div>
      <el-dialog
      title="用户注册"
      :visible.sync="showRegister"
      width="40%"
      center>
      <span>
        <el-form :label-position="labelPosition" :rules="rules" label-width="80px" :model="userModel">
         <el-form-item label="用户名">
         <el-input v-model="userModel.username"></el-input>
         </el-form-item>
         <el-form-item label="密码">
          <el-input v-model="userModel.password"></el-input>
         </el-form-item>
         <el-form-item label="重复密码">
          <el-input v-model="userModel.repassword"></el-input>
         </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="showLogin = true;showRegister = false">返回登录</el-button>
      <el-button @click="register">注册</el-button>
      </span>
      </el-dialog>
    </div>

</div>

</template>

<script setup>
import PersonCard from "@/components/PersonCard.vue";
import ChatWindow from "./chatwindow.vue";
import { useRoute } from 'vue-router';
import { getFriendService,addFriendService,getHistoryService,delFriendService2,delFriendService1, addFriendService1 } from "@/api/getData";
//用户相关接口
import { RegisterService, LoginService } from "@/api/account";
import { ref, onMounted } from 'vue';
import { Dialog, Message } from "element-ui";
import { useMyStore } from "@/stores/token";

const store = useMyStore();
const isLogin = store.isLogin
//当前打开的会话对象id
const pcCurrent = ref('');


//会话对象列表相关----------------------------------------------------------------------------------------------------
//会话对象列表
const personList = ref([{
  D_id: "dialogue456",
  Type: "chat",
  //time: "2024-05-17 10:32:00",
  Content: {
  role: "user",
  message: "Hello, how can I help you?"}
},
]);


const getList=async()=>{
  let DataObj ={
    user_id:user_id.value,
  }
  let res = await getFriendService(DataObj);
  personList.value = res.data.data;

}


//绘图对话列表
const showChatWindow = ref(true);
//会话对象详细信息
const chatWindowInfo = ref({});

const labelPosition=ref('left');
const showLogin = ref(false);
const showRegister = ref(false);
const user_id = ref('');



//用户模型
const userModel = ref({
  id:'',
  username:'',
  password:'',
  repassword:''
})

//历史记录模型(目前用不到)
const history = ref([
  {

  },
])

//获取历史聊天记录
const getHistory = async()=>{
  let res = await getHistoryService(pcCurrent.value);
  history.value = res.data.data;

}

//点击后打开聊天窗口
const clickPerson = (info) => {
  showChatWindow.value = true;
  chatWindowInfo.value = info;
  console.log("点击对象的属性"+info)
  pcCurrent.value = info.id;
  getHistory();
};




//用户登录相关----------------------------------------------------------------------------------------------
//判断当前登录状态
const isLoginOrNot = ()=>{
  if(!isLogin){
    console.log('登录状态无')
    showLogin.value = true
    showChatWindow.value=false
  }
  else
  console.log('登录状态有')
}

isLoginOrNot();

//密码校验
const checkRePassword = (rule,value,callback)=>{
    if(value ===''){
        callback(new Error('亲，再次确认密码'))
    }else if(value!==userModel.value.password){
        callback(new Error('亲，确保两次输入密码一致'))
    }else{
        callback()
    }
    
}

//elementplus提供的校验规则
//定义表单校验规则
const rules={
    username:[
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 5,max: 16,message: '5-16位非空字符', trigger: 'blur' }
    ], 
    password:[
    {required:true,message:"请输入密码",trigger:'blur'},
        {min:5,max:16,message:"5-16位非空字符",trigger:'blur'}
    ],
    repassword:[
        {validator:checkRePassword,trigger:'blur'}
    ]

}

const register = async()=>{
    let DataObj = {
        id:userModel.value.id,
        username:userModel.value.username,
        password:userModel.value.password
    }
  
    if(userModel.value.password!=userModel.value.repassword&&userModel.value.username){
    try {
    result = await RegisterService(DataObj);
    if (result.statusCode === 200) { // 假设200表示成功
    showRegister.value=false
    Message({
          message: '注册成功了亲',
          center: true,
          type: 'success'
        })
    showLogin.value = true
    } else {
    // 处理非200状态码的情况
    throw new Error(`请求失败，状态码：${result.statusCode}`);
    }
    } catch (error) {
    // 处理错误
    }
     
  }
       
}

const login = async() =>{
    let DataObj = {
        username:userModel.value.username,
        password:userModel.value.password
    }
    let result = await LoginService(DataObj)
    try {
    result = await LoginService(DataObj);
    if (result.statusCode === 200) { // 假设200表示成功
    showRegister.value=false
    Message({
          message: '登录成功了亲',
          center: true,
          type: 'success'
        })
    showLogin.value = true
    user_id.value = userModel.value.username;
    store.set()
    } else {
    // 处理非200状态码的情况
    throw new Error(`请求失败，状态码：${result.statusCode}`);
    }
    } catch (error) {
    // 处理错误
    }
    //登录成功后，渲染时调用一次
    getList();
    clearRegisterData()
}

const clearRegisterData = ()=>{
    userModel.value={
        username:'',
        password:'',
        repassword:''
    }
}

//会话对象相关-------------------------------------------------------------------------------------------
//新增会话对象的函数
//待修改，nowfunc已弃用
const add = async()=>{
  try {
    let result = await addFriendService(user_id.value)
    if (result.statusCode === 200) { // 假设200表示成功
    showRegister.value=false
    Message({
          message: '添加成功了亲',
          center: true,
          type: 'success'
        })
    showLogin.value = true
    user_id.value = userModel.value.username;
    store.set()
    } else {
    // 处理非200状态码的情况
    throw new Error(`请求失败，状态码：${result.statusCode}`);
    }
    } catch (error) {
    // 处理错误
    }
  getList();
}

//删除会话对象
const del = async()=>{
      let DataObj ={
        Did:this.pcCurrent,
        user_id:this.user_id,
      }
      try {
        let result = await delFriendService1(DataObj);
      if (result.statusCode === 200) { // 假设200表示成功
      showRegister.value=false
      Message({
          message: '删除成功了亲',
          center: true,
          type: 'success'
        })
      showLogin.value = true
      } else {
      // 处理非200状态码的情况
      throw new Error(`请求失败，状态码：${result.statusCode}`);
      }
      } catch (error) {
      // 处理错误
      }
      
      this.getList();
    
}
</script>

<style lang="scss" scoped>
.chatHome {
  // margin-top: 20px;
  display: flex;
  .chatLeft {
    width: 280px;
    .title {
      color: #fff;
      padding-left: 10px;
    }
    .online-person {
      margin-top: 60px;
      .onlin-text {
        padding-left: 10px;
        color: rgb(176, 178, 189);
      }
      .person-cards-wrapper {
        padding-left: 10px;
        height: 65vh;
        margin-top: 20px;
        overflow: hidden;
        overflow-y: scroll;
        box-sizing: border-box;
        &::-webkit-scrollbar {
          width: 0; /* Safari,Chrome 隐藏滚动条 */
          height: 0; /* Safari,Chrome 隐藏滚动条 */
          display: none; /* 移动端、pad 上Safari，Chrome，隐藏滚动条 */
        }
      }
    }
  }

  .chatRight {
    flex: 1;
    padding-right: 30px;
    .showIcon {
      position: absolute;
      top: calc(50% - 150px); /*垂直居中 */
      left: calc(50% - 50px); /*水平居中 */
      .icon-snapchat {
        width: 300px;
        height: 300px;
        font-size: 300px;
        // color: rgb(28, 30, 44);
      }
    }
  }
}

.add_btn{
  margin-left: 90px;
  position: absolute;
  float: left;

}

</style>
